package tomcat.ch02;

import tomcat.ch02.adaptor.ResponseAdaptor;

import java.io.*;

public class Response extends ResponseAdaptor {

    public static final int BUFFER_SIZE = 1024;
    Request request;
    OutputStream output;
    PrintWriter writer;

    public Response(OutputStream output) {
        this.output = output;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    /**
     * This method is used to serve static pages
     *
     * @throws IOException
     */
    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try {
            File file = new File(Constants.WEB_ROOT, request.getUri());
            fis = new FileInputStream(file);
            int ch = fis.read(bytes, 0, BUFFER_SIZE);
            while (ch != -1){
                output.write(bytes, 0, ch);
                ch = fis.read(bytes, 0, BUFFER_SIZE);
            }
        } catch (Exception e) {
            String errorMessage;
            StringBuilder sbb = new StringBuilder();
            sbb.append("HTTP/1.1 404 File Not Found\r\n");
            sbb.append("Content-Type: text/html\r\n");
            sbb.append("Content-Length: 23\r\n");
            sbb.append("\r\n");
            sbb.append("<h1>File Not Found</h1>");
            errorMessage = sbb.toString();
            output.write(errorMessage.getBytes());
        } finally {
            if(fis != null){
                fis.close();
            }
        }

    }

    @Override
    public PrintWriter getWriter() throws IOException {
        // autoFlush is true, println() will flush,
        // but print() will not
        writer = new PrintWriter(output, true);
        return writer;
    }
}
